#!/usr/bin/env python
#coding=utf-8
# Copyrignt (c) xuzeshui.com. All Rights Reserved.
# Author: Zeshui Xu<i@xuzeshui.com>
# Created Time: 2016-03-09 18:59:37
# Last Modified: 2017-04-20 13:46:47
# File Name: geturl.py
# Description:

__version__ = "0.1"
__all__ = []

import os
import sys
import hashlib
import json
import copy
import time
import random

host = "xzs.app.qkier.com:8091"
#host = "openapi.qkier.com"
salt = "88366f9fad954828a194f3232a78a471"
default_params = {
    "appkey": "140a6d51",
    "time": int(time.time())
}

def convert2utf8(input_val):
    """ 
        转成utf8格式
    """
    if isinstance(input_val, dict):
        return {convert2utf8(key):convert2utf8(value) for key,value in input_val.iteritems()}
    elif isinstance(input_val, list):
        return [convert2utf8(element) for element in input_val]
    elif isinstance(input_val, unicode):
        return input_val.encode('utf-8')
    else:
        return input_val

def get_nonce():
    nonce_str = "0123456789abcdefghijklmnopqrstuvwxyz"
    arr = []
    for i in xrange(0, 5):
        arr.append(nonce_str[random.randint(0, len(nonce_str) - 1)])
    return "".join(arr)

def get_url(path, params):
    myparams = copy.deepcopy(default_params)
    myparams.update(params)
    myparams["nonce"] = get_nonce()
    myparams = convert2utf8(myparams)
    keys = myparams.keys()
    keys.sort()
    calc_arr = []
    for key in keys:
        calc_arr.append(key)
        calc_arr.append(str(myparams[key]))
    calc_arr.append(salt)
    m = hashlib.md5()
    m.update("".join(calc_arr))
    sign = m.hexdigest()
    myparams["sign"] = sign
    qs_arr = []
    for k, v in myparams.iteritems():
        qs_arr.append("%s=%s" % (k, v))
    qs = "&".join(qs_arr)
    return "https://%s%s?%s" % (host, path, qs)



if __name__  == "__main__":
    if len(sys.argv) != 3:
        print "%s [path] [params]" % sys.argv[0]
        sys.exit(1)
    path = sys.argv[1]
    params = json.loads(sys.argv[2])
    print get_url(path, params)
